package twitter

import (
	"../../restc"
	"strconv"
)

type User struct {
	ID int "user_id"
	ScreenName string "screen_name"
	Cursor int "cursor"
}

type UserInfo struct {
	ID int `json:"id"`
	ScreenName string `json:"screen_name"`
	Description *string `json:"description"`
	Location *string `json:"location"`
}

type Hashtag struct {
}

type Mention struct {
	Name string `json:"name"`
	ID int `json:"id"`
}

type URL struct {
	Expanded string `json:"expanded_url"`
	Shortened string `json:"url"`
}

type Entities struct {
	Hashtags []Hashtag `json:"hashtags"`
	URLs []URL `json:"urls"`
	Mentions []Mention `json:"user_mentions"`
}

type Status struct {
	User UserInfo `json:"user"`
	Text string `json:"text"`
	Entities Entities `json:"entities"`
}

type Retweet struct {
	User UserInfo `json:"user"`
	Text string `json:"text"`
	Entities Entities `json:"entities"`
	RetweetOf Status `json:"retweeted_status"`
}

type idlist struct {
	Next int `json:"next_cursor"`
	IDs []int `json:"ids"`
}

func UserByID(id int) User {

	return User{ID:id}
}

func UserByName(name string) User {

	return User{ScreenName:name}
}

func (u *User) GetID() int {

	if u.ID == 0 {
		u.GetInfo()
	}

	return u.ID
}

func (u *User) GetName() string {

	if u.ScreenName == "" {
		u.GetInfo()
	}

	return u.ScreenName
}

func (u *User) GetInfo() (info UserInfo, err error) {

	const base = "https://api.twitter.com/1/users/show.json?"

	err = restc.Get(base, *u, &info)

	u.ID = info.ID
	u.ScreenName = info.ScreenName

	return
}

func (u *User) URI() string {

	const base = "https://api.twitter.com/1/users/show.json?"

	if u.ID == 0 {
		_, err := u.GetInfo()

		if err != nil {
			panic (err)
		}
	}

	return base + "?user_id=" + strconv.Itoa(u.ID)
}

func (u *User) GetFollowerIDs() (ids []int, err error) {

	const base = "https://api.twitter.com/1/followers/ids.json?"

	for cursor := -1; cursor != 0; {

		segment := idlist{}

		err = restc.Get(base, *u, &segment)

		if err != nil {
			return
		}

		ids = append(ids, segment.IDs ...)

		cursor = segment.Next
	}

	return
}

func (u *User) GetFriendIDs() (ids []int, err error) {

	const base = "https://api.twitter.com/1/friends/ids.json?"

	for cursor := -1; cursor != 0; {

		segment := idlist{}

		err = restc.Get(base, *u, &segment)

		if err != nil {
			return
		}

		ids = append(ids, segment.IDs ...)

		cursor = segment.Next
	}

	return
}

// recent retweets posted by the given user
func (u *User) GetRetweets() (statuses []Retweet, err error) {

	const base = "https://api.twitter.com/1/statuses/retweeted_by_user.json?include_entities=true"

	err = restc.Get(base, *u, &statuses)

	return
}
